package list.control;

import list.model.Contact;
import list.model.Tag;
import list.model.Telephone;
import list.model.User;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

/**
 * Created by ZhipengLi.
 */
public class FileConverter {
    private static final String CHARSET = "UTF-8";

    public static String createVcf(String content) {
        String file = (new Date()).getTime() + ".vcf";
        String download = "../../download/" + file;
        String fileName = "/var/www/jsp/download/" + file;
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(new File(fileName));
            fileOutputStream.write(content.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return download;
    }

    public static String makeVcf(User user, int tag_id) {
        if (tag_id != 0) {
            return makeVcf(user.getContacts(tag_id), Tag.getTagName(user.getUser_id(), tag_id));
        } else {
            return makeVcf(user.getContacts(), "未分组");
        }
    }

    private static String makeVcf(Contact[] contacts, String tag_name) {
        StringBuilder output = new StringBuilder();
        for (Contact contact : contacts) {
            output.append(headOfVcf(contact.getName())).append(cell(contact.getTelephones())).append(groupOfVcf(tag_name)).append(companyOfVcf(contact.getAddress())).append(jobOfVcf(contact.getWork_place())).append(endOfVcf());
        }
        return output.toString();
    }

    /*public static String analyzeVcf() {
        String name = "=E5=A4=A7=E5=AD=A6".replace("=", "%");
        //String name = "%E6%9D%A8%E6%B7%91%E7%91%9C";

        try {
            return URLDecoder.decode(name, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String changeToXml() {
        //将数据整理生成xml文件，返回文件链接
        String xmlHead = "<?xml version=\"1.0\"?>\n";
        *//*Master master = new Master("111");
        String[] users = new String[master.getFriends().size()];
        for (int item = 0; item < master.getFriends().size(); item++) {
            users[item] =
        }
        String body = ;*//*
        return null;
    }

    public static String changeToTxt() {
        //将数据整理生成txt文件，返回文件链接
        return null;
    }

    public static String changeToHtml() {
        //将数据整理生成html文件，返回文件链接
        return null;
    }

    public static String changeToJson() {
        //将数据整理生成json文件，返回文件链接
        return null;
    }*/

    private static String utf8(String target) {
        try {
            return URLEncoder.encode(target, CHARSET).replace("%", "=");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String cell(Telephone[] telephones) {
        if (telephones == null) return "";
        int length = telephones.length;
        if (length == 0) return "";
        String[] cells = new String[length];
        int i = 0;
        cells[i] = cellUnit(telephones[i], true);
        while (++i < length) {
            cells[i] = cellUnit(telephones[i], false);
        }
        return toString(cells);
    }

    private static String cellUnit(Telephone telephone, boolean isFirst) {
        if (telephone == null) return "";
        String type = telephone.getType();
        if (isFirst) {
            type += ";PREF";
        }
        return "\nTEL;" + type + ":" + telephone.getPhone_number();
    }

    private static String toString(String[] cells) {
        if (cells == null) return "";
        StringBuilder stringBuilder = new StringBuilder();
        for (String cell : cells) {
            stringBuilder.append('\n').append(cell);
        }
        return stringBuilder.toString();
    }

    private static String headOfVcf(String name) {
        if (name == null) return "";
        String nameUtf = utf8(name);
        return "BEGIN:VCARD\nVERSION:2.1\nN;CHARSET=" + CHARSET + ";ENCODING=QUOTED-PRINTABLE:" + nameUtf + ";;;;\nFN;CHARSET=" + CHARSET + ";ENCODING=QUOTED-PRINTABLE:" + nameUtf;
    }

    private static String groupOfVcf(String tag_name) {
        return "\nCATEGORIES;CHARSET=" + CHARSET + ";ENCODING=QUOTED-PRINTABLE:" + utf8(tag_name);
    }

    private static String companyOfVcf(String address) {
        if (address == null) return "";
        return "\nORG;CHARSET=" + CHARSET + ";ENCODING=QUOTED-PRINTABLE:" + utf8(address);
    }

    private static String jobOfVcf(String job) {
        if (job == null) return "";
        return "\nTITLE;CHARSET=" + CHARSET + ";ENCODING=QUOTED-PRINTABLE:" + utf8(job);
    }

    private static String endOfVcf() {
        return "\nEND:VCARD\n";
    }


    private static String tag(String key, String value) {
        return "<" + key + ">" + value + "</" + key + ">";
    }
}
